package org.ishequ.http;

import java.io.File;

import org.ishequ.service.AddressService;
import org.ishequ.service.NewsService;
import org.ishequ.utils.FormFile;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Android_HttpActivity extends Activity {
	
	private EditText nameText ;
	private EditText timeText ;
	private EditText fileText ;
	private EditText phoneText ;
	private TextView content ;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nameText = (EditText) findViewById(R.id.name);
        timeText = (EditText) findViewById(R.id.timelen);
        fileText = (EditText) findViewById(R.id.filename);
        phoneText = (EditText) findViewById(R.id.phoneno);
        content = (TextView) findViewById(R.id.content);
    }
    
    public void submit(View v){
    	String name = nameText.getText().toString().trim();
    	String timelen = timeText.getText().toString().trim();
    	String filename = fileText.getText().toString().trim();
    	
    	if("".equals(fileText.getText().toString().trim())){
    		boolean result = false;
			try {
				result = NewsService.save(name,timelen,"UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
    		if(result){
    			Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT);
    		}else{
    			Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_SHORT);
    		}
    	}else{
    		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)||
    				Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
    			File uploadfile = new File(Environment.getDataDirectory(),filename);
    			if(uploadfile.exists()){
    				FormFile formFile = new FormFile(uploadfile, "imgfile", "image/gif");
    				boolean result = false;
					try {
						result = NewsService.saveWithFile(name,timelen,formFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
    				if(result){
    					Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT);
    				}else{
    					Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_SHORT);
    				}
    			}else{
    				Toast.makeText(getApplicationContext(), R.string.filenotfound, Toast.LENGTH_SHORT);
    			}
    		}else{
    			Toast.makeText(getApplicationContext(), R.string.filenotfound, Toast.LENGTH_SHORT);
    		}
    			
    	}
    }
    
    public void query(View v){
    	try {
    		content.setText(AddressService.getAddress(phoneText.getText().toString()));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}